<script>
const updateManager = uni.getUpdateManager();

import { mapState } from "vuex";
export default {
  data() {
    return {
      option: {},
      launchOption: {},
      invite_id: "", //邀请人id
    };
  },
  computed: {
    // ...mapState([''])
  },
  onLaunch: function () {
    console.warn("App.vue onLaunch");
    // this.handleLaunchParams(option);
    //this.setView();

    // #ifdef MP
    // this.queryLocation();
    // #endif
  },
  onShow: function () {
    console.warn("App.vue onShow");
    this.handleLaunchParams();
    this.checkVersionUpdate();
  },
  onHide: function () {
    console.log("App Hide");
  },
  methods: {
    //1 用户扫好友邀请码 - query.scene
    //2 通过邀请链接进入 -
    handleLaunchParams() {
      // let option = uni.getLaunchOptionsSync();
      let option = uni.getEnterOptionsSync();
      this.launchOption = option;
      console.log("启动参数 getEnterOptionsSync option", option);

      let that = this;
      let invite_id = ""; //邀请人id

      try {
        if (option) {
          let query = option.query;
          if (query) {
            // 1 用户分享链接进入
            // 2 用户分享产品海报二维码进入
            // 3 用户分享邀请海报二维码进入
            if (query.invite_id) {
              //1 分享链接进入
              invite_id = query.invite_id;
            } else if (query.scene) {
              //2 扫分享海报二维码进入
              let scene = decodeURIComponent(query.scene);
              let paramsArr = scene.split("&");
              let paramsObj = {};
              paramsArr.forEach((keyValStr) => {
                let keyVal = keyValStr.split("=");
                let key = keyVal[0];
                let val = keyVal[1];
                paramsObj[key] = val;
              });

              if (paramsObj["invite_id"]) {
                invite_id = paramsObj["invite_id"];
              }
            }

            console.warn("App.vue 业务参数 invite_id = ", invite_id);
            if (invite_id) {
              this.$store.commit("cache_invite_id", invite_id);
            }
          }
        }
      } catch (e) {
        console.log("App.vue handleInvite", e);
      }

      this.invite_id = invite_id;
      this.checkLogin();
    },

    setView() {
      this.$store.dispatch("getConfig");
      // this.checkLogin()

      // uni.login({
      // 	provider: 'weixin',
      // 	success: (e) => {
      // 		this.weixin_login(e.code);
      // 	}
      // });
    },

    checkLogin() {
      // #ifdef H5
      this.$store.commit("set_test_user_in_web");
      // #endif
      let token = uni.getStorageSync("token");
      console.warn("App.vue checkLogin 获取 token", token);

      if (token) {
        this.$api({
          url: "/service.php",
          method: "get",
          data: {
            action: "users_userInfo",
          },
        }).then((res) => {
          console.log("App.vue 用户信息", res);
          if (res.code == 200) {
            this.$store.commit("set_vuex_user", res.data);
          } else {
            this.$store.commit("remove_vuex_user", false);
            // 处理 手机端和PC同时登录小程序 引起的登录失效问题
            this.get_weixin_code();
            //
          }
        });
      } else {
        this.get_weixin_code();
      }
    },

    //获取登录code
    get_weixin_code() {
      // #ifndef WEB
      uni.login({
        provider: "weixin",
        success: (e) => {
          this.weixin_login(e.code);
        },
      });
      // #endif
    },

    //微信登录
    weixin_login(code) {
      console.log("小程序登录 邀请人id = ", this.invite_id);
      //
      this.$api({
        url: "/service.php",
        method: "post",
        data: {
          action: "login_miniLogin", //login
          code: code,
          invite_id: this.invite_id || "",
        },
      }).then((res) => {
        this.$logjson("login", res);
        if (res.code == 200) {
          let data = res.data;
          this.query_user(data);
        } else {
          this.$alert("小程序登录失败");
        }
      });
    },
    //查询用户信息
    query_user(data) {
      this.$api({
        url: "/service.php",
        method: "post",
        data: {
          action: "users_userInfo", //login
          userId: data.userId || "",
          token: data.token || "",
          // code: code,
          // invite_id: this.invite_id
        },
      }).then((res) => {
        if (res.code == 200) {
          let data = res.data;
          this.$store.commit("set_vuex_user", data);
          // this.myInfo = data;
          // this.has_avatar = !!data.image;
          // this.has_phone = !!data.username;
          // this.session_key = data.session_key || '';
        }
      });
    },

    //获取地理位置
    queryLocation() {
      //用户选择的位置
      let cache_select_location = uni.getStorageSync("cache_select_location");
      let cache_default_location = uni.getStorageSync("cache_default_location");
      console.log("App cache_select_location", cache_select_location);
      console.log("App cache_default_location", cache_default_location);
      //获取缓存位置  如果没有缓存位置  则需要重新定位
      if (!cache_default_location) {
        // 		uni.getLocation({
        // 			type: 'wgs84',
        // 			success: (res) => {
        // 				// debugger
        // 				// console.log('******* 查询地理位置信息 *******', res)
        // 				// console.log('当前位置的经度：' + res.longitude);
        // 				// console.log('当前位置的纬度：' + res.latitude);
        // 				this.queryAddressByPoi({
        // 					weidu: res.latitude,
        // 					jingdu: res.longitude,
        // 				});
        // 			}
        // 		});

        console.warn("授权查询");
        uni.authorize({
          scope: "scope.userLocation",
          success: (res) => {
            console.warn("authorize success", res);
            uni.getLocation({
              type: "gcj02", //wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
              success: (res) => {
                this.$log("地理位置 success", res);
                let longitude = res.longitude;
                let latitude = res.latitude;
                let point = {
                  longitude: longitude,
                  latitude: latitude,
                };
                // this.$store.dispatch('saveUserLocation', point)
                this.$store.commit("set_vuex_default_location", point);
                // this.queryAddressByPoi(point);
              },
              fail: (err) => {
                console.warn("getLocation fail", err);
              },
            });
          },
          fail: (err) => {
            console.warn("authorize fail", err);
            this.$alert("请开启小程序获取位置设置");
            // this.$api({
            // 	url: '/query_user',
            // 	method: 'get',
            // 	data: {},
            // }).then(res => {
            // 	console.log("获取用户信息中保存的地理位置", res);
            // 	if (res.code == 200) {
            // 		let longitude = res.data.longitude;
            // 		let latitude = res.data.latitude;
            // 		if (longitude && latitude) {
            // 			let point = {
            // 				longitude: longitude,
            // 				latitude: latitude
            // 			}
            // 			this.$store.commit('set_vuex_default_location', point)
            // 			// this.queryAddressByPoi(point);
            // 		}
            // 	}
            // });
          },
        });
        console.warn("授权查询2");
      } else {
        if (cache_select_location) {
          this.$store.commit("set_vuex_select_location", cache_select_location);
        }
        if (cache_default_location) {
          this.$store.commit(
            "set_vuex_default_location",
            cache_default_location
          );
        }
      }
    },

    //根据经纬度获取地理位置
    queryAddressByPoi(poi) {
      //接口文档 https://lbs.qq.com/service/webService/webServiceGuide/address/Gcoder
      //逆地址解析 - 由经纬度到文字地址
      //https://apis.map.qq.com/ws/geocoder/v1/?location=38.894185,115.467761&key=4WFBZ-D5JCZ-6AQXF-ZLFQT-DWLI2-P2BZ7
      let { latitude, longitude } = poi;

      let request_params = `location=${latitude},${longitude}`;
      this.$api({
        url: "/geocoder",
        method: "get",
        data: {
          type: 0, //0 腾讯 1 百度 2 高德
          request_url: request_params,
        },
      }).then((res) => {
        // this.$log('地图地址解析 geocoder res', res);
        if (res.code == 200) {
          try {
            let result = res.data.result;
            if (result) {
              let address_component = result.address_component;
              if (address_component) {
                let {
                  //
                  nation,
                  province,
                  city,
                  district,
                  street,
                  street_number,
                } = address_component;

                let location_title =
                  street_number || street || district || city;

                this.$store.commit("set_vuex_default_location", {
                  location_title: location_title,
                  latitude: latitude,
                  longitude: longitude,
                });
              }
            }
          } catch (e) {}
        }
      });

      // uni.request({
      // 	url: 'https://apis.map.qq.com/ws/geocoder/v1/',
      // 	method: 'GET',
      // 	data: {
      // 		key: MAP_SDK_APPID,
      // 		location: `${latitude},${longitude}`, //经纬度（GCJ02坐标系）  示例 location= 39.984154,116.307490
      // 	},
      // 	success: (res) => {
      // 		console.log('腾讯地图service api获取 逆地址解析结果', res);
      // 		try {
      // 			let result = res.data.result
      // 			if (result) {
      // 				let address_component = result.address_component
      // 				if (address_component) {
      // 					let {
      // 						//
      // 						nation,
      // 						province,
      // 						city,
      // 						district,
      // 						street,
      // 						street_number
      // 					} = address_component;

      // 					let location_title = street_number || street || district || city;

      // 					this.$store.commit('set_vuex_default_location', {
      // 						location_title: location_title,
      // 						latitude: latitude,
      // 						longitude: longitude,
      // 					})
      // 				}
      // 			}
      // 		} catch (e) {

      // 		}
      // 	}
      // });
    },

    //
    checkVersionUpdate() {
      if (updateManager) {
        updateManager.onCheckForUpdate(function (res) {
          console.log("版本更新", res.hasUpdate); // 请求完新版本信息的回调
        });

        updateManager.onUpdateReady(function (res) {
          uni.showModal({
            title: "更新提示",
            content: "新版本已经准备好，是否重启应用？",
            success(res) {
              if (res.confirm) {
                updateManager.applyUpdate(); // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
              }
            },
          });
        });

        updateManager.onUpdateFailed(function (res) {
          // 新的版本下载失败
          uni.showModal({
            title: "更新提示",
            content:
              "新版本更新失败，为了获得更好的体验，请您删除当前小程序，重新搜索打开",
            success(res) {
              if (res.confirm) {
                updateManager.applyUpdate(); // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
              }
            },
          });
        });
      }
    },
  },
};
</script>

<style lang="scss">
/* 注意要写在第一行，同时给style标签加入lang="scss"属性 */
@import "@/uni_modules/uview-ui/index.scss";
@import "@/config/base.scss";
page {
  height: 100%;
  background: #f6f6f6;
}
</style>
